package com.luguotao.lease.common.utils;

import com.luguotao.lease.common.exception.LeaseException;
import com.luguotao.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    //毫秒为单位，不要设置太短，否则在网页中要经常登录
    private static long expireTime = 1000*60*60;       //一个小时
    //此方法要求使用sha256bit来加密
    private static SecretKey secretKey = Keys.hmacShaKeyFor("8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92".getBytes());
    //生成token
    //也可以传其他，都是成为token的负载，作为用户的唯一标识
    //负载的七个字段
    public static String creatToken(Long id,String userName){
        String token = Jwts.builder()
                //主题
                .setSubject("sysUser-token")
                //过期时间设置
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                //负载，要携带的内容
                .claim("userId",id)
                .claim("userName",userName)
                //用密钥签名
                .signWith(secretKey)
                //打包压缩
                .compressWith(CompressionCodecs.GZIP)
                //整理
                .compact();
        return token;
    }


    //解析token
    public static Claims parseToken(String token){
        //把密钥放进去用于解析
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);

            //获取负载数据
            Claims body = claimsJws.getBody();
            return body;

            //过期异常
        } catch (ExpiredJwtException e) {
            //也可以抛自己的异常
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    //测试生成的token
    public static void main(String[] args) {
        String token = creatToken(666L,"zhangfei");
        System.out.println(token);

        //可以测试一下过期
//        try {
//            Thread.sleep(3333);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        Claims claims = parseToken(token);
        System.out.println(claims.get("userId"));
        System.out.println(claims.get("userName"));
    }
}
